package org.springframework.security.samples.service;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.samples.entity.UserInfo;
import org.springframework.security.samples.entity.UserJpaRepository;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * Created by lzx on 16/7/14.
 */
@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    UserJpaRepository userJpaRepository;

    /**
     * 需要自定义jdbc源,实现UserDetailsService接口并复写规则
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<UserInfo> userInfo = userJpaRepository.findByUsername(username);
        if(userInfo.isPresent()) {
            GrantedAuthority authority = new SimpleGrantedAuthority(userInfo.get().getRole());
            UserDetails userDetails = new User(userInfo.get().getUsername(),userInfo.get().getPassword(), Lists.newArrayList(authority));
            return userDetails;
        }
        return null;
    }
}
